package cn.itenzo.good.service.impl;

import cn.itenzo.common.validate.LengthValidate;
import cn.itenzo.common.validate.MoneyValidate;
import cn.itenzo.common.validate.NotBlankValidate;
import cn.itenzo.common.vo.RetMsg;
import cn.itenzo.good.dao.GoodMapper;
import cn.itenzo.good.model.Good;
import cn.itenzo.good.service.GoodService;
import com.alibaba.dubbo.config.annotation.Service;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.Result;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.github.abel533.entity.Example;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by ENZO on 2017/5/23.
 */
@Component("goodService")
@Service
public class GoodServiceImpl implements GoodService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodServiceImpl.class);

    @Autowired
    private GoodMapper goodMapper;


    @Override
    public RetMsg addGood(Good entity) {

        LOGGER.info("添加商品: {}" , ReflectionToStringBuilder.toString(entity));


        HashMap<Object, Object> hashMap = new HashMap<>();

        FluentValidator fluentValidator = FluentValidator.checkAll();
        Result result = fluentValidator
                .on(entity.getGoodStoreId()+"" , new NotBlankValidate("门店ID"))   //门店ID
                .on(entity.getGoodName(), new LengthValidate(3, 30, "商品名称"))
                .on(entity.getGoodItemId()+"", new NotBlankValidate("分类ID"))
                .on(String.valueOf(entity.getGoodPrice()), new MoneyValidate())
                .on(entity.getGoodNuit(), new NotBlankValidate("单位"))
                .on(entity.getGoodDesc(), new LengthValidate(5, 200, "商品描述"))
                .doValidate().result(ResultCollectors.toSimple());

        if(!result.isSuccess()){

            LOGGER.warn("warn:{}",ReflectionToStringBuilder.toString(result.getErrors().get(0)));

            return RetMsg.error(result.getErrors().get(0));
        }

        entity.setGoodStatus("1");              //正常状态，不上架
        entity.setDelState(new Byte("2"));  //不进行删除
        entity.setRecommend(new Byte("2"));//默认不推荐
        entity.setGoodCtime(new Date());           //创建时间

        int i = goodMapper.insertSelective(entity);

        hashMap.put("code",i);
       return RetMsg.success("0",i);
    }


    /**
     * 修改商品价格
     *
     * @param goodId
     * @param price
     * @return
     * @throws Exception
     */
    @Override
    public RetMsg updatePrice(Long goodId, BigDecimal price) throws Exception {

        LOGGER.info("修改商品价格 ==> 商品ID:{},金额:{}",goodId,price.toString() );

        Good good = new Good();
        good.setGoodId(goodId);
        good.setGoodPrice(price);
        goodMapper.updateByPrimaryKeySelective(good);
        return RetMsg.success("0","修改成功");
    }

    /**
     * 修改商品名称
     *
     * @param goodId
     * @param goodName
     * @return
     * @throws Exception
     */
    @Override
    public RetMsg updateGoodName(Long goodId, String goodName) throws Exception {

        LOGGER.info("修改商品价格 ==> 商品ID:{},修改商品名称:{}",goodId,goodName);

        Good good = new Good();
        good.setGoodId(goodId);
        good.setGoodName(goodName);
        goodMapper.updateByPrimaryKeySelective(good);
        return RetMsg.success("0","修改成功");
    }

    /**
     * 修改整个商品
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @Override
    public Map updateGood(Good entity) throws Exception {

        goodMapper.updateByPrimaryKeySelective(entity);
        return null;
    }

    /**
     * 推荐
     *
     * @param goodId
     * @return
     */
    @Override
    public RetMsg recommend(Long goodId) throws Exception {

        LOGGER.info("推荐商品 ==> 商品ID:{}", goodId);

        Good good = new Good();
        good.setGoodId(goodId);
        good.setRecommend(new Byte("1"));
        int i = goodMapper.updateByPrimaryKeySelective(good);
        return RetMsg.success("推荐成功",i);
    }

    /**
     * 取消推荐
     *
     * @param goodId
     * @return
     */
    @Override
    public RetMsg unReCommend(Long goodId) throws Exception {
        LOGGER.info("取消推荐商品 ==> 商品ID:{}", goodId);
        Good good = new Good();
        good.setGoodId(goodId);
        good.setRecommend(new Byte("2"));
        int i = goodMapper.updateByPrimaryKeySelective(good);
        return RetMsg.success("取消成功",i);
    }

    /**
     * 商品上架
     *
     * @param goodId
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public RetMsg pushGood(Long goodId) throws Exception {

        LOGGER.info("上架商品 ==> 商品ID:{}", goodId);
        Good good = new Good();
        good.setGoodId(goodId);
        good.setGoodStatus("2");
        int i = goodMapper.updateByPrimaryKeySelective(good);
        if(i == 1){
           return RetMsg.success("修改成功",null);
        }else if(i==0){
            return RetMsg.error("修改失败");
        }else if(i > 1){
             throw new Exception("修改失败,进行回滚");
        }
        return RetMsg.error("修改失败");
    }


    /**
     * 批量上架商品
     *
     * @param goodId
     * @return
     * @throws Exception
     */
    @Override
    public Map bathPushGood(Long[] goodId) throws Exception {


        LOGGER.info("批量上架商品 ==> 商品ID:{}", ReflectionToStringBuilder.toString(goodId));
        Good good = new Good();
        good.setGoodStatus("2");

        ArrayList<Object> list = new ArrayList<>();

        for (Long o :goodId) {
            list.add(o);
        }


        Example example = new Example(Good.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("goodId", list);
        goodMapper.updateByExampleSelective(good,example);
        return null;
    }

    /**
     * 下架商品
     *
     * @param goodId
     * @return
     * @throws Exception
     */
    @Override
    public RetMsg pushDownGood(Long goodId) throws Exception {
        LOGGER.info("下架商品 ==> 商品ID:{}", ReflectionToStringBuilder.toString(goodId));

        Good good = new Good();
        good.setGoodId(goodId);
        good.setGoodStatus("1");
        int i = goodMapper.updateByPrimaryKeySelective(good);
        if(i == 1){
            return RetMsg.success("下架成功",null);
        }else if(i==0){
            return RetMsg.error("下架失败");
        }else if(i > 1){
            throw new Exception("下架失败,进行回滚");
        }
        return RetMsg.error("下架失败");
    }

    /**
     * 批量下架商品
     *
     * @param goodId
     * @return
     * @throws Exception
     */
    @Override
    public Map bathPushDownGood(Long[] goodId) throws Exception {
        LOGGER.info("批量下架商品 ==> 商品ID:{}", ReflectionToStringBuilder.toString(goodId));

        Good good = new Good();
        good.setGoodStatus("2");

        ArrayList<Object> list = new ArrayList<>();

        for (Long o :goodId) {
            list.add(o);
        }


        Example example = new Example(Good.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("goodId", list);
        goodMapper.updateByExampleSelective(good,example);
        return null;
    }


    @Override
    public PageInfo<Good> queryPageByStore(Good good, int page, int limit, String orderClause) {
        PageHelper.startPage(page,limit);

        Example example = new Example(Good.class);
        example.setOrderByClause(orderClause);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("goodStoreId",good.getGoodStoreId());
        List<Good> goods = goodMapper.selectByExample(example);
        PageInfo info = new PageInfo<>(goods);
        return info;
    }
}
